/*
 * @Author: fengshan0525 2735332396@qq.com
 * @Date: 2023-03-17 20:43:12
 * @LastEditors: fengshan525 2735332396@qq.com
 * @LastEditTime: 2023-10-20 21:19:53
 * @FilePath: \b-vue3-ts-ele-template\src\router\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { App } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { routes } from '@/router/baseRoutes'
import { getCookies } from '@/utils/storage'
import { TokenKey } from '#/constant'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { menuStore } from '@/store/modules/menu'
import { userStore } from '@/store/modules/user'
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

NProgress.configure({
  easing: 'ease', // 动画方式
  speed: 500, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3 // 初始化时的最小百分比
})

// 白名单
const whiteList = ['/login', '/register', '/preview']

/** 描述： global router guard */
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getCookies(TokenKey)) {
    const menuPinia = menuStore()
    const userPinia = userStore()
    // 已经获取到用户的信息了，便不再重复请求
    if (userPinia.hasUserInfo) {
      next()
    } else {
      // 获取路由
      userPinia.queryUserInfo()
      menuPinia.getRouters().then(accessRoutes => {
        accessRoutes.forEach(element => {
          router.addRoute(element) // 动态添加可访问路由表
        })
        router.addRoute({ path: '/:catchAll(.*)', redirect: '/404' })
        next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
      })
    }
  } else {
    // 免登录白名单
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login') // 重定向到首页
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export function setupRouter (app: App<Element>) {
  app.use(router)
}
